#!/usr/bin/python
# -*- coding:utf-8 -*-

#########################
#
#  版本要求：python3
#
#########################

#http://tushare.org/index.html
#pip install tushare
#import requests
#import random
import tushare as ts
import os
from os import system
import threading
import time
import datetime
import json
import re
import math
import sys
import copy
import re
#import webbrowser
from pidModule import ifProcessRunning
#pip install texttable
from texttable import Texttable

# 获取当前文件（即该Python脚本）所在的目录
current_directory = os.path.dirname(__file__)

#调用了一个免费的股票数据接口baostock提供的历史行情数据和实时数据
#http://baostock.com/baostock/index.php/%E9%A6%96%E9%A1%B5

system("title gp") #给终端命名
max_width=268
os.system("mode con cols="+str(max_width)+" lines=78")#设置控制台尺寸

# 获取当前脚本所在目录路径
#script_dir = os.path.dirname(os.path.realpath(__file__))

#pidPath = "cls.pid"
# 检查进程是否存在的例子
#runFlag = ifProcessRunning(pidPath)
#若原程序在执行中，则退出
#if runFlag == False: 
    #打开财联社网页版电报
    #webbrowser.open('https://www.cls.cn/telegraph')
    #打开财联社新终端
#    command ="python "+current_directory+"/cls.py" #命令
#    os.system("start cmd /c "+command)
    # sleep一下，因为windows11打开cmd比较慢，为了防止界面还没出现而误触，这样做一下比较保险
#    time.sleep(0.2)

if ifProcessRunning('tushareLimit.pid') == False: 
    #打开涨停池
    #打开财联社新终端
    command ="python "+current_directory+"/tushareLimit.py" #命令
    os.system("start cmd /c "+command)
    # sleep一下，因为windows11打开cmd比较慢，为了防止界面还没出现而误触，这样做一下比较保险
    time.sleep(0.3)

def get_data_from_api(api_url):  
    try:
        # 发送GET请求   
        #headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36'}
        # 关闭不必要连接
        requests.DEFAULT_RETRIES = 5
        s = requests.session()
        s.keep_alive = False
        # proxy = {"http": "xxfb.mwr.cn:8080"}
        user_agent_list = [
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36",
            "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
            "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
            "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36",
            "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36",
            "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)",
            "Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10.5; en-US; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15"
        ]
        
        headers = {
            'User-Agent': '',
            'Content-Type': 'application/json;charset=UTF-8',
            'Request Method': 'GET',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'
        }
        headers['User-Agent'] = random.choice(user_agent_list)
        response = requests.get(api_url, headers=headers,timeout=30)
        # 检查请求是否成功  
        if response.status_code == 200:  
            # 解析返回的JSON数据  
            data = response.json()  
            return data  
        else:  
            print(f"请求失败，状态码：{response.status_code}")  
            exit()
    except Exception as e:
        print(f"异常信息：{str(e)}")
        exit()

def generate_time_strings(date,delta_seconds=5):
    
    start_time1 = datetime.datetime.strptime(date+" 09:25:00", "%Y-%m-%d %H:%M:%S")
    end_time1 = datetime.datetime.strptime(date+" 11:30:00", "%Y-%m-%d %H:%M:%S")
    time_strings = []
    current_time1 = start_time1
    while current_time1 <= end_time1:
        time_strings.append([current_time1.strftime("%H:%M:%S"),'0'])
        current_time1 += datetime.timedelta(seconds=delta_seconds)

    start_time2 = datetime.datetime.strptime(date+" 13:00:00", "%Y-%m-%d %H:%M:%S")
    end_time2 = datetime.datetime.strptime(date+" 15:00:00", "%Y-%m-%d %H:%M:%S")
    current_time2 = start_time2
    while current_time2 <= end_time2:
        time_strings.append([current_time2.strftime("%H:%M:%S"),'0'])
        current_time2 += datetime.timedelta(seconds=delta_seconds)

    return {'date':date,'list':time_strings}


#判断字符串是否只包含英文字母和数字
def is_english_and_number(string):
    pattern = r'^[a-zA-Z0-9]+$'
    if re.match(pattern, string):
        return True
    else:
        return False 


# 修改舍入方式为四舍五入，解决round 遇5不进的问题
def round_up_down(dst,num = 2):
    dst = float(dst)
    if(dst * pow(10,num+1)%10 == 5):
        ans = math.ceil(dst * pow(10, num)) / pow(10, num)
    else:
        ans = round(dst, num)
    return ans

todayTime = datetime.date.today()

amStartTime = datetime.datetime(year=todayTime.year, month=todayTime.month, day=todayTime.day, hour=9, minute=25)
amEndTime = datetime.datetime(year=todayTime.year, month=todayTime.month, day=todayTime.day, hour=11, minute=30)

pmStartTime = datetime.datetime(year=todayTime.year, month=todayTime.month, day=todayTime.day, hour=13, minute=00)
pmEndTime = datetime.datetime(year=todayTime.year, month=todayTime.month, day=todayTime.day, hour=15, minute=00)

#开市时间、闭市时间
# 09:15 11:30 13:00 15:00
amStart = 915
amEnd = 1130
pmStart = 1300
pmEnd = 1500


#gpCode = ['sh', 'cyb','sz','sz50', 'hs300', 'zxb', '603178', '002855', '002456']    # ['sh','sz','hs300','sz50','zxb','cyb']
f = open(current_directory+"/tushare_code.txt",'r')        # txt文件，存储股票代码，一行一个代码，小写字母，换行为换行显示，#为注释
gpCode = [line.strip() for line in f.readlines()]
gpCodeList = [x for x in gpCode if x is not None and x != "" and is_english_and_number(x) == True] #过滤空的换行
gpCodeList = [s.strip() for s in gpCodeList if s.strip()] #去掉前后空格
f.close()


#打开并读取txt文件内容
with open(current_directory+'/tushare_seconds_price.txt', 'r') as file:
    price_seconds_txt_content = file.read()
if price_seconds_txt_content.strip() != "" :
    #将txt内容转换为JSON格式
    price_seconds_json_data = json.loads(price_seconds_txt_content)
else:
    #初始化
    todayStr = todayTime.strftime("%Y-%m-%d")
    # 获取今天的日期
    today = datetime.datetime.now()
    # 获取昨天的日期
    yesterday = today - datetime.timedelta(days=1)
    yesterdayStr = yesterday.strftime("%Y-%m-%d")

    #避免报错
    price_seconds_json_data = []
    price_seconds_json_data.append(generate_time_strings(yesterdayStr))
    price_seconds_json_data.append(generate_time_strings(todayStr))


#打开并读取txt文件内容
with open(current_directory+'/tushare_price.txt', 'r') as file:
    price_txt_content = file.read()
if price_txt_content.strip() != "" :
    #将txt内容转换为JSON格式
    price_json_data = json.loads(price_txt_content)
else:
    #避免报错
    price_json_data = {}

#默认数据对象
price_json_data_default = {
    "9:25":"0","9:30":"0","9:35":"0","9:40":"0","9:45":"0","9:50":"0","9:55":"0",
    "10:00":"0","10:05":"0","10:10":"0","10:15":"0","10:20":"0","10:25":"0","10:30":"0","10:35":"0","10:40":"0","10:45":"0","10:50":"0","10:55":"0",
    "11:00":"0","11:05":"0","11:10":"0","11:15":"0","11:20":"0","11:25":"0","11:30":"0",
    "13:05":"0","13:10":"0","13:15":"0","13:20":"0","13:25":"0","13:30":"0","13:35":"0","13:40":"0","13:45":"0","13:50":"0","13:55":"0",
    "14:00":"0","14:05":"0","14:10":"0","14:15":"0","14:20":"0","14:25":"0","14:30":"0","14:35":"0","14:40":"0","14:45":"0","14:50":"0","14:55":"0","15:00":"0"
}

showName = False  #是否显示全称
refreshTime = 3.0  #自动刷新时间
showRecentDate = 10 #展示的最近天数



#获取最近的时间数组(包括今天)
def get_recent_dates(num):
    if num < 3:
        print("目前只支持3天以上的时间")
        exit()

    dates = []
    for i in range(0, num+1):
        date = todayTime - datetime.timedelta(days=i)
        formatted_date = f"{date:%Y-%m-%d}"
        dates.append(formatted_date)
    
    return dates


#计算涨停价格，涨停价格计算原理
#limit_price = pre_close + pre_close * 0.1
#对涨停价格limit_price做四舍五入
def limit_up_price(pre_close,limit):
    if pre_close == 0:
        return 0
    pre_close = float(pre_close)
    limit = float(limit)

    limit_price = pre_close * (1+limit)
    limit_price = str(round_up_down(limit_price))
    return limit_price

def limit_down_price(pre_close,limit):
    if pre_close == 0:
        return 0
    pre_close = float(pre_close)
    limit = float(limit)
    
    limit_price = pre_close * (1-limit)
    limit_price = str(round_up_down(limit_price))
    return limit_price

def check_stock_exchange(code,codeName):
    # 定义不同市场的规则
    shanghai = r'^60[0-9]{4}$'   # 上海A股
    shenzhen = r'^00[0-9]{4}$'   # 深圳A股或者中小企业挂牌公司
    chuangye = r'^30[0-9]{4}$'   # 创业板
    kechuan = r'^68[0-9]{4}$'   # 科创版
    beijiao = r'^82|83|87|88[0-9]{4}$'   #北交所股票代码开头是82、83、87、88,主要以8开头
    
    #返回涨跌幅限制，0.1为10cm，即10%
    if re.match(shanghai, code):
        exchange = 0.1
    elif re.match(shenzhen, code):
        exchange = 0.1
    elif re.match(chuangye, code):
        exchange = 0.2
    elif re.match(kechuan, code):
        exchange = 0.2
    elif re.match(beijiao, code):
        exchange = 0.3
    else:
        exchange = 0.1

    if ("ST" in codeName or "st" in codeName) and exchange == 0.1 :
        exchange = 0.05

    return exchange


#倒计时，秒
def countdown(seconds):
    while seconds > 0:
        sec = seconds % 60
        minute = seconds / 60 % 60
        hour = seconds / 60 / 60
        hour = math.floor(hour)  # 去掉小数点，向下取整
        minute = math.floor(minute)  # 去掉小数点，向下取整

        sys.stdout.write('\r' + "距离自动刷新还剩" + str(hour) + "小时" + str(minute) + "分钟" + str(sec) + "秒")
        sys.stdout.flush()
        time.sleep(1)
        seconds -= 1

#生成连续分钟的数组
def createMinuteResultList(minute):
    if minute < 3:
        print("目前只支持3分钟以上的间隔时间")
        exit()

    start_time = datetime.datetime(year=todayTime.year, month=todayTime.month, day=todayTime.day, hour=9, minute=25)
    end_time = start_time + datetime.timedelta(hours=5, minutes=35) # 计算结束时间，今天下午3点（从起始时间加上5小时35分）
    
    minuteResultList = []
    current_time = start_time
    while current_time <= end_time:
        if amStartTime <= current_time <= amEndTime or  pmStartTime < current_time <= pmEndTime  :
            minuteResultList.append(str(current_time))
        current_time += datetime.timedelta(minutes=minute)  #每5分钟一个元素
    return minuteResultList



#获取最近30天的时间
date_result_list = get_recent_dates(30)
#量能间隔时间，如有修改需清空tushare_price.txt文件内容，否则报错
minuteInterval = 5
#生成连续分钟的数组
minuteResultList = createMinuteResultList(minuteInterval)

#刷新股票行情
def refreshData():
    global timer
    timer = threading.Timer(refreshTime, get, [])
    timer.start()

#判断数组长度 不足则空格填充
def pad_array_with_spaces(arr, desired_length,str = ' '):
    while len(arr) < desired_length:
        arr.append(str)
    return arr


def get():
    # Windows平台上的命令为"cls"，Linux/Mac平台上的命令为"clear"
    commandCls = "cls" if os.name == 'nt' else "clear"
    os.system(commandCls)   # 清屏操作

    # 获取当前时间
    now = datetime.datetime.now()
    # 计算明天的日期
    tomorrow = now + datetime.timedelta(days=1)
    nowTimeInt = int(now.strftime("%H%M"))
    nowDayHourInt = int(now.strftime("%Y%m%d%H"))
    nowYear = str(now.strftime("%Y"))
    dayOfWeek = now.isoweekday()
    
    try:
        #获取股票列表接口，请求多个股票方法（一次最好不要超过30个）
        codeList = ts.get_realtime_quotes(gpCodeList)
    except Exception as e:
        print("tushare接口，捕获到异常了！")
        print(f"异常类型：{type(e)}")
        print(f"异常信息：{str(e)}")
        #倒计时
        countdown(6)
        #自动刷新行情
        refreshData()
        exit()
    #finally:
        #print("无论是否有异常都会执行该部分代码")
    #print(codeList)
    printTableData = printTable(codeList)


    #工作日,开市时间
    if (amStart <= nowTimeInt <= amEnd or pmStart <= nowTimeInt <= pmEnd) and  printTableData.get('isTradeDate') == True :
        #自动刷新行情
        refreshData()

    #未开盘时间段，倒计时等待行情刷新
    if (amEnd < nowTimeInt < pmStart or nowTimeInt < 915 or pmEnd < nowTimeInt < 2359) and  printTableData.get('isTradeDate') == True :
        #开盘时间
        if  nowTimeInt < 915:
            specified_time = datetime.datetime(todayTime.year, todayTime.month, todayTime.day, 9, 15, 0)
        elif 1130 <= nowTimeInt < 1300:
            specified_time = datetime.datetime(todayTime.year, todayTime.month, todayTime.day, 13, 00, 0)
        elif 1500 <= nowTimeInt < 2358:
            specified_time = datetime.datetime(tomorrow.year, tomorrow.month, tomorrow.day, 9, 15, 0)
        # 计算时间差
        delta = specified_time - now
        seconds_difference = int(delta.total_seconds())
        #中午指定睡眠时间，避免无必要的刷新
        if seconds_difference > 0:
            #倒计时
            countdown(seconds_difference)
            #自动刷新行情
            refreshData()
            exit()

#输出表格
def printTable(codeList):
    # 创建一个Texttable实例
    table = Texttable()
    # Texttable设置表头
    tableHeader = ['服务器名称','云编码/%','量能/亿','存储/元','服务器代码',' ','服务器名称','云编码/%','量能/亿','存储/元','服务器代码',' ','服务器名称','云编码/%','量能/亿','存储/元','服务器代码',' ','服务器名称','云编码/%','量能/亿','存储/元','服务器代码'];
    tableHeaderLen = len(tableHeader)
    table.header(tableHeader)
    table.set_chars(['-', '|', '+', '-'])
    table.set_max_width(max_width)
    #print(gpCode)
    #exit()
    num = 0
    tablenum = 1
    listNextNum = 0;
    volumePrice = 0;
    add_row = [];
    #print(codeList)
    for code in gpCode: 
        listNextNum=listNextNum+1
        if code is None or code == "":
            tablenum = 1
            #print('换行')
            table.add_row(pad_array_with_spaces([],tableHeaderLen, ' '))
            continue
        if is_english_and_number(code) != True:
            continue


        nowPrice = str(round_up_down(codeList['price'][num]))

        # 计算涨跌停
        limitUp = ''
        limitDown = ''
        stock_exchange = check_stock_exchange(codeList['code'][num],codeList['name'][num])
        limitUp = limit_up_price(codeList['pre_close'][num],stock_exchange) #涨停
        limitDown = limit_down_price(codeList['pre_close'][num],stock_exchange) #跌停
        
            

        limitMark = '***'
        limitMarkPre = '***'
        if code.isdigit():
            #判断是否为纯数字代码，加空格，容易区分
            limitMark = ' '+'***'
            limitMarkPre = '***'+' '

        if nowPrice == limitUp:
            #涨停
            limitMarkPre = '@@ '
            limitMark = "[Zt] @@"
            
        elif nowPrice == limitDown:
            #跌停
            limitMarkPre = '## '
            limitMark = "(Dt) ##"


        priceRange = round((float(codeList['price'][num]) - float(codeList['pre_close'][num])) / float(codeList['pre_close'][num]) * 100, 2)

        if priceRange > 3 and nowPrice < limitUp:
            #涨幅大于3，并且未涨停
            limitMarkPre = '*++ '
            limitMark = " ++*"

        if priceRange > 5 and nowPrice < limitUp:
            #涨幅大于5，并且未涨停
            limitMarkPre = '+++ '
            limitMark = " +++"

        if priceRange < -3 and nowPrice > limitDown:
            #涨幅小于3，并且未跌停
            limitMarkPre = '*-- '
            limitMark = " --*"

        if priceRange < -5 and nowPrice > limitDown:
            #涨幅小于5，并且未跌停
            limitMarkPre = '--- '
            limitMark = " ---"
            

        codeName = codeList['name'][num]
        codeName = codeName.replace(" ", "") 
        if showName == False:
            if "ST" in codeName or "st" in codeName :
                codeName =  limitMarkPre + codeName[:5]  + limitMark  #st
            else:
                if len(codeName) <= 3 or "上海" in codeName or "中国" in codeName  or "四川" in codeName :
                    #上海开头的票太多，只屏蔽最后一个字
                    codeName =  limitMarkPre + codeName[:-1] + limitMark  #屏蔽最后1个字
                else:    
                    codeName =  limitMarkPre + codeName[:-2] + limitMark  #屏蔽最后2个字


        codeAmount = round(float(codeList['amount'][num])/ 100000000,2)
        #成交量，万手
        codeVolume = round(float(codeList['volume'][num])/ 1000000,2)

        row = [codeName,str(priceRange),codeAmount,nowPrice, '**' +codeList['code'][num] + '**']
        if len(add_row) != 0:
            add_row.append('');


        #下一个为换行
        if listNextNum < len(gpCode):
            huanhang = (gpCode[listNextNum] is None or gpCode[listNextNum] == "")
        else:
            huanhang = True
        #huanhang = listNextNum in len(gpCode) and (gpCode[listNextNum] is None or gpCode[listNextNum] == "")
        #print(num+1,tablenum%3,listNextNum,codeList['code'][num],codeName,huanhang,gpCode[listNextNum])
        #最后一个，或，下一个为换行
        if(  huanhang and ( tablenum%4!=0 ) or ( (num+1) == len(codeList) and  tablenum%4!=0 ) ):
            #print('补全')
            add_row = add_row + row
            
            add_row = pad_array_with_spaces(add_row,tableHeaderLen, ' ')
            tablenum=1
        else:
            add_row=add_row+row;
            tablenum=tablenum+1
            

        if(len(add_row) == tableHeaderLen):
            #print(add_row)
            table.add_row(add_row)
            add_row = [];
            
        
        if(code == 'sh' or code == 'sz'):
            volumePrice = str(round(round(float(volumePrice),2)+round(float(codeAmount),2),2))

        num=num+1
        
    #输出texttable
    print(table.draw())
    priceWriteData = priceWrite(volumePrice)
    print("")

    print("当前时间："+ str(datetime.datetime.now())) 

    return {"volumePrice":volumePrice,'isTradeDate':priceWriteData.get('isTradeDate')}


#写入量能
def priceWrite(volumePrice):

    
    todayStr = todayTime.strftime("%Y-%m-%d")
    now_time = datetime.datetime.now()
    # 获取昨天的日期
    yesterday = now_time - datetime.timedelta(days=1)
    yesterdayStr = yesterday.strftime("%Y-%m-%d")

    #写入实时量能 start
    price_seconds_json_today = {}
    price_seconds_json_yesterday = {}
    price_seconds_json_yesterday_volume = 0
    price_seconds_json_yesterday_data = []
    #判断今天数据是否存在
    isSetTodayData = False
    price_seconds_json_data2 = price_seconds_json_data
    for item2 in price_seconds_json_data2:
        if todayStr == item2['date']:
            isSetTodayData = True
            price_seconds_json_today = item2
            break
        
    if isSetTodayData == False:
        #不存在则新增数据
        price_seconds_json_today = generate_time_strings(todayStr)
        price_seconds_json_data2.append(price_seconds_json_today)
        

    if len(price_seconds_json_data2) > 2:
        #只保留2天的数据
        price_seconds_json_data2 = price_seconds_json_data2[-2:]

    #处理完数据后再获取昨天的数据
    price_seconds_json_yesterday = price_seconds_json_data2[0]

    secondsLen = len(price_seconds_json_today['list'])
    for key3 in range(0, secondsLen-1):    
        current_element = datetime.datetime.strptime(todayStr+" "+price_seconds_json_today['list'][key3][0], "%Y-%m-%d %H:%M:%S")
        next_element = datetime.datetime.strptime(todayStr+" "+price_seconds_json_today['list'][key3+1][0], "%Y-%m-%d %H:%M:%S")
        if current_element < now_time <= next_element:
            price_seconds_json_today['list'][key3][1] = volumePrice
            price_seconds_json_yesterday_volume = float(price_seconds_json_yesterday['list'][key3][1])
            if key3 > 0 and now_time >= datetime.datetime.strptime(todayStr+" 09:30:00", "%Y-%m-%d %H:%M:%S") and float(price_seconds_json_yesterday['list'][key3-1][1]) and float(price_seconds_json_yesterday['list'][key3][1]) and float(price_seconds_json_yesterday['list'][key3+1][1]) > 0:
                #取平均，减少误差
                price_seconds_json_yesterday_volume = (float(price_seconds_json_yesterday['list'][key3-1][1])+float(price_seconds_json_yesterday['list'][key3][1])+float(price_seconds_json_yesterday['list'][key3+1][1]))/3

            price_seconds_json_yesterday_data = price_seconds_json_yesterday['list'][key3]
            #print(price_seconds_json_yesterday['list'][key3-1])
            #print(price_seconds_json_yesterday['list'][key3])
            #print(price_seconds_json_yesterday['list'][key3+1])

        if  now_time >= datetime.datetime.strptime(todayStr+" 14:59:00", "%Y-%m-%d %H:%M:%S"):
            #print([volumePrice,now_time,datetime.datetime.strptime(todayStr+" 14:59:00", "%Y-%m-%d %H:%M:%S"),price_seconds_json_today['list'][secondsLen-1][1]])
            #exit()
            #补全最后的15:00数据
            price_seconds_json_today['list'][secondsLen-1][1] = volumePrice
    

    if  now_time >= datetime.datetime.strptime(todayStr+" 15:00:00", "%Y-%m-%d %H:%M:%S"):
        price_seconds_json_yesterday_volume = price_seconds_json_yesterday['list'][secondsLen-1][1]
        price_seconds_json_yesterday_data = price_seconds_json_yesterday['list'][secondsLen-1]

    #if  now_time <= datetime.datetime.strptime(todayStr+" 09:30:00", "%Y-%m-%d %H:%M:%S"):
    #    price_seconds_json_yesterday_volume = price_seconds_json_yesterday['list'][0][1]

    key2 = 0;
    for item2 in price_seconds_json_data2:
        if todayStr == item2['date']:
            price_seconds_json_data2[key2]= price_seconds_json_today
            break;
        key2=key2+1
    
    with open(current_directory+'/tushare_seconds_price.txt', 'w') as file:
        file.write(json.dumps(price_seconds_json_data2))#将JSON数据转换为字符串形式
    #写入实时量能 end
    



    isTradeDate = True #默认为新的交易日
    price_show_data = [] #展示数据的数组

    #数据处理
    price_save_data = list(price_json_data)
    for item in date_result_list:
        if item not in price_save_data:
            #添加默认数据
            price_json_data[item] = copy.deepcopy(price_json_data_default) #修改深拷贝列表的值，避免后面修改值被取了内存地址导致同时被修改
        for json_date in price_save_data:            
            if item == json_date:
                #添加到展示数组
                if json_date != todayStr and price_json_data[json_date]["15:00"] != "0":
                    price_show_data.append(price_json_data[json_date])
                #当前量能额如果和其中一天收盘量能一致，则不是新的交易日（必须不等于今天，尾盘还有集合竞价成交量）
                if json_date != todayStr and str(volumePrice) == str(price_json_data[json_date]['15:00']):
                    isTradeDate = False
                #跳出当前循环
                break


    #需展示的有数据的数组不足设定的天数，则补全数组，否则调用会报错
    price_show_data_len = len(price_show_data)
    if price_show_data_len < showRecentDate:
        price_show_data += [price_json_data_default for _ in range(showRecentDate - price_show_data_len)]

    
    minuteLen = len(minuteResultList)

    writeTime = ''
    #展示最近的数据
    showTime = '';
    for key in range(0, minuteLen-1):
        # 获取当前元素和后面一个元素
        current_element = datetime.datetime.strptime(minuteResultList[key], "%Y-%m-%d %H:%M:%S")
        next_element = datetime.datetime.strptime(minuteResultList[key+1], "%Y-%m-%d %H:%M:%S")

        if current_element <= now_time < next_element:
            if next_element.minute < 10:#前面补0，否则报错
                next_minute = '0' + str(next_element.minute)
            else:
                next_minute = str(next_element.minute)
            
            showTime = str(next_element.hour) + ":" + next_minute

            #因为目前5分钟量能时段统计，为了减少误差，结束时间减2分钟再生成写入时间
            next_element_reduce = next_element - datetime.timedelta(minutes=2) #减2分钟
            if next_element_reduce <= now_time < next_element:
                writeTime = str(next_element.hour) + ":" + next_minute

            break
  
    if pmEndTime <= now_time:
        writeTime = '15:00'
        showTime = '15:00'
    if amStartTime > now_time :
        writeTime = '9:25'
        showTime = '9:25'


    if float(price_seconds_json_yesterday_volume) > 0:
        volumeYesterday = float(price_seconds_json_yesterday_volume)
    else:
        #volumeYesterday = float(price_show_data[0][showTime]) #偏差较大，不使用
        volumeYesterday = 0

    

    changePer = 0
    if volumeYesterday > 0:

        changeVolume = math.ceil(float(volumePrice)-float(volumeYesterday))

        changePer = round(float(changeVolume)/float(volumeYesterday)*100,2);
        if changePer > 15:
            volumeForecast = float(price_show_data[0]['15:00'])+changeVolume
        else:
            volumeForecast = round(float(price_show_data[0]['15:00']) * (changePer+100)/100,2);

        if changeVolume > 0:
            changeVolume = "+"+str(changeVolume)

        if changePer > 0:
            changePer = "+"+str(changePer)+"%"

        volStr = str(math.ceil(float(price_show_data[0]['15:00']))) + " * " + str(math.ceil(float(price_show_data[1]['15:00'])))+" * " + str(math.ceil(float(price_show_data[2]['15:00'])))+" * " + str(math.ceil(float(price_show_data[3]['15:00'])))+" * " + str(math.ceil(float(price_show_data[4]['15:00'])))

        volumeStr = " * " + "较上一日量能变化："+ str(changeVolume) + " * 实时量能变化："+str(changePer)+"%" + " * [ 今日预测量能："+str(math.ceil(float(volumeForecast)))+" * 近5日量能："+volStr+" ]"
    else:
        volumeStr = ' * 实时or预测量能因数据缺失，暂无计算结果'



    #print(price_seconds_json_yesterday_data)
    print("今日当前量能总计："+ str(math.ceil(float(volumePrice))) + volumeStr)


    showStr = '';
    for i in range(0, showRecentDate):
        separator = " * " 
        if i == (showRecentDate-1):
            separator = ""
        showStr += str(math.ceil(float(price_show_data[i][showTime]))) + separator

    print("近"+str(showRecentDate)+"日"+showTime+"量能："+ showStr)

    #必须是带有写入时间才能写入
    if(writeTime != '' and isTradeDate == True):
        price_json_data[todayStr][writeTime] = volumePrice
        #将JSON数据转换为字符串形式
        price_json_str = json.dumps(price_json_data)#保存数据
        with open(current_directory+'/tushare_price.txt', 'w') as file:
            file.write(price_json_str)




    return {"isTradeDate":isTradeDate}


if __name__ == "__main__":

    timer = threading.Timer(refreshTime, get, [])
    timer.start()

